﻿using System.Reflection;
using Tetris.Game.ControlsBase.Common;

namespace Tetris.Game.Common
{
    public static class EnumEx
    {
        public static string DisplayText(this Enum value)
        {
            FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
            object[] attributes = fieldInfo.GetCustomAttributes(typeof(DisplayTextAttribute), false);
            DisplayTextAttribute customAttribute = attributes.FirstOrDefault() as DisplayTextAttribute;
            if (customAttribute == null)
            {
                return value.ToString();
            }

            return customAttribute.DisplayText;
        }

        public static TEnum ToEnum<TEnum>(this string dataToMatch, bool ignoreCase = true) where TEnum : struct
        {
            if (!dataToMatch.InEnum<TEnum>()())
            {
                return (TEnum)Enum.Parse(typeof(TEnum), dataToMatch, ignoreCase);
            }

            return default(TEnum);
        }

        public static Func<bool> InEnum<TEnum>(this string dataToCheck) where TEnum : struct
        {
            return () => string.IsNullOrEmpty(dataToCheck) || !Enum.IsDefined(typeof(TEnum), dataToCheck);
        }
        /// <summary>
        /// 获取枚举所有值
        /// </summary>
        /// <returns></returns>
        public static List<InfoIdValue> GetListAllEnumType<T>(this Type type) where T : struct
        {
            if (!type.IsEnum)
                return null;

            var enumValues = Enum.GetValues(type);
            var list = new List<InfoIdValue>();
            foreach (Enum value in enumValues)
            {
                list.Add(new InfoIdValue
                {
                    Id = value.GetHashCode().ToString(),
                    Value = value.DisplayText(),
                    Value2 = value.ToString(),
                });
            }
            return list;
        }
        /// <summary>
        /// 获取枚举所有值
        /// </summary>
        /// <returns></returns>
        public static List<InfoIdValue> GetListAllEnumType(this Type type)
        {
            if (!type.IsEnum)
                return null;

            var enumValues = Enum.GetValues(type);
            var list = new List<InfoIdValue>();
            foreach (Enum value in enumValues)
            {
                list.Add(new InfoIdValue
                {
                    Id = value.GetHashCode().ToString(),
                    Value = value.DisplayText(),
                    Value2 = value.ToString(),
                });
            }
            return list;
        }
    }
}
